import emojiRegex from "emoji-regex"

import { TOAST_METHOD } from "@/components/messages"

export const REG_USER_NAME = /^[A-Za-z]{1}(?=(.*[a-zA-Z]){0,})(?=(.*[0-9]){1,})[0-9A-Za-z]{3,10}$/
export const REG_PASSWORD = /^([a-zA-Z0-9]*[a-zA-Z]+[0-9]+[a-zA-Z0-9]*|[a-zA-Z0-9]*[0-9]+[a-zA-Z]+[a-zA-Z0-9]*)$/
export const REG_PAY_PASSWORD = /^[A-Za-z0-9]{6,12}$/

export const PASSWORD_TIP = "限制6～12位，字母+数字组合"
export const PAY_PASSWORD_TIP = "密码6-12位数字或字母"
export const LOGIN_AND_REGISTER_PASSWORD_TIP = "请输入8~12位字母+数字组合的密码"
const REG_VALID_USER = /^[a-zA-Z0-9]{4,11}$/
// 手机验证码
export const REG_CODE = /^[0-9]{6}$/
// 输入数字
export const REG_NUMBER = /^[0-9]*$/

// 用户名正则，1到12位（中文、字母、数字）
export const USERNAME_1_12 = /^[\u4e00-\u9fa50-9A-Z-a-z]{1,12}$/
// 真实姓名正则，1到32位（中文、字母、数字）
export const USERNAME_1_32 = /^[\u4e00-\u9fa5A-Z-a-z]{1,32}$/
// 性别 0女 1男 -1未设置
export const REG_SEX = /[0|1]/
// 只能输入汉字字母数字正则(过滤特殊字符)
export const REG_NO_SPECIAL_CHAR = /[^a-zA-Z0-9\u4E00-\u9FA5]/g
// 只能输入汉字 正则(过滤其他所有字符)
export const REG_ONLY_CHINESE_NO_OTHERS = /[^\u4E00-\u9FA5]+$/
// 只能输入汉字字母正则(过滤特殊字符)
export const REG_NO_SPECIAL_CHAR_AND_NUMBER = /[^a-zA-Z\u4E00-\u9FA5]/g
// 匹配中文
export const REG_ONLY_CHINESE = /^[\u4E00-\u9FA5]+$/
// 银行卡号
export const REG_BANK_CARD = /^[1-9]\d{15,18}$/

// 只允许输入数字
export const validatorOnlyNumber = (_: any, value: any) => {
	return REG_NUMBER.test(value) ? Promise.resolve() : Promise.reject(new Error("请输入数字"))
}

export const validUserName = (val: string) => {
	if (!val) {
		return false
	}

	return REG_VALID_USER.test(val)
}

export const validatorNickname = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请输入昵称"))
	} else {
		return USERNAME_1_12.test(value) ? Promise.resolve() : Promise.reject(new Error("请输入中文、字母、数字"))
	}
}

export const validatorRealName = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请输入姓名"))
	} else if (value.length < 2 || value.length > 20) {
		return Promise.reject(new Error("姓名验证失败"))
	} else {
		return USERNAME_1_32.test(value) ? Promise.resolve() : Promise.reject(new Error("请输入中文"))
	}
}

/* 银行卡真实姓名校验 */
export const validatorBankerRealName = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请输入真实名称"))
	} else if (value.length < 2 || value.length > 20) {
		return Promise.reject(new Error("请输入2-20位真实名称"))
	} else {
		return REG_ONLY_CHINESE.test(value) ? Promise.resolve() : Promise.reject(new Error("请输入中文"))
	}
}

export const validLoginAndPassword = (_: any, value: string) => {
	if (!value) {
		return Promise.reject(new Error(LOGIN_AND_REGISTER_PASSWORD_TIP))
	}

	if (value.length < 8) {
		return Promise.reject(new Error(LOGIN_AND_REGISTER_PASSWORD_TIP))
	}

	return REG_PASSWORD.test(value) ? Promise.resolve() : Promise.reject(new Error(LOGIN_AND_REGISTER_PASSWORD_TIP))
}

export const validPassword = (_: any, value: string) => {
	if (!value) {
		return Promise.reject(new Error(PASSWORD_TIP))
	}

	if (value.length < 6) {
		return Promise.reject(new Error(PASSWORD_TIP))
	}

	return REG_PASSWORD.test(value) ? Promise.resolve() : Promise.reject(new Error(PASSWORD_TIP))
}

export const validPayPassword = (_: any, value: string) => {
	if (!value) {
		return Promise.reject(new Error(PAY_PASSWORD_TIP))
	}

	if (value.length < 6) {
		return Promise.reject(new Error(PAY_PASSWORD_TIP))
	}

	return REG_PAY_PASSWORD.test(value) ? Promise.resolve() : Promise.reject(new Error(PAY_PASSWORD_TIP))
}

export const validatorSex = (_: any, value: any) => {
	if (value === -1) {
		return Promise.reject(new Error("请选择性别"))
	}
	return REG_SEX.test(value) ? Promise.resolve() : Promise.reject(new Error("请选择性别"))
}

export const validatorBankCardAmount = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请选择金额"))
	}
	return value > 0 ? Promise.resolve() : Promise.reject(new Error("请选择金额"))
}

export const validatorUsdtAmount = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请选择或输入金额"))
	}
	return value > 0 ? Promise.resolve() : Promise.reject(new Error("请选择或输入金额"))
}

export const validatorCancelBankRepositReason = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请选择取消原因"))
	}
	return value > 0 ? Promise.resolve() : Promise.reject(new Error("请选择取消原因"))
}

export const validatorUploadCertificate = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请上传凭证"))
	}
	return value.length > 0 ? Promise.resolve() : Promise.reject(new Error("请上传凭证"))
}

export const validatorDepositName = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请输入转账持卡人名称"))
	} else if (value.length < 2 || value.length > 20) {
		return Promise.reject(new Error("姓名仅支持汉字输入2-20个字汉字长度"))
	} else {
		return REG_ONLY_CHINESE.test(value) ? Promise.resolve() : Promise.reject(new Error("姓名仅支持汉字输入2-20个字汉字长度"))
	}
}

export const validatorBankCard = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请输入银行卡号"))
	} else {
		return REG_BANK_CARD.test(value) ? Promise.resolve() : Promise.reject(new Error("银行卡号格式错误"))
	}
}
export const validatorPsw = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请输入银行卡号"))
	} else {
		console.log(/^\d$/.test(value))
		return /^\d$/.test(value) ? Promise.resolve() : Promise.reject(new Error("请输入数字"))
	}
}

export const regCode = (_: any, value: any) => {
	if (!value) {
		return Promise.reject(new Error("请输入验证码"))
	} else {
		return REG_CODE.test(value) ? Promise.resolve() : Promise.reject(new Error("请输入6位验证码"))
	}
}

export const validateIp = (formatMessage: Function, value: string): Promise<void> => {
	const regular =
		/^((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))$/
	let arr: string | any[] = []

	if (value && value.includes("，")) {
		let str = ""
		str = value.replace(/，/g, ",")
		arr = str.split(",")
	} else if (value) {
		arr = value.split(",")
	} else {
		return Promise.reject(formatMessage({ id: "risk.required" }))
	}
	if (arr.length > 0) {
		const flag = []
		for (let i = 0; i < arr.length; i++) {
			const ele = arr[i]
			if (ele && !regular.test(ele)) {
				flag.push(i + 1)
			}
		}
		if (flag.length) {
			return Promise.reject(
				formatMessage({ id: "risk.format_error" }) +
					flag.join(formatMessage({ id: "risk.section" })) +
					formatMessage({ id: "risk.individual" })
			)
		} else {
			return Promise.resolve()
		}
	}
	return Promise.resolve()
}

export const validateIpNoRegular = (formatMessage: Function, value: string) => {
	let arr: string | any[] = []
	if (value && value.includes("，")) {
		let str = ""
		str = value.replace(/，/g, ",")
		arr = str.split(",")
	} else if (value) {
		arr = value.split(",")
	} else {
		Promise.reject(formatMessage({ id: "risk.required" }))
	}
	if (arr.length > 0) {
		const flag = []
		for (let i = 0; i < arr.length; i++) {
			const ele = arr[i]
			if (ele && ele.length > 100) {
				flag.push(i + 1)
			}
		}
		if (flag.length) {
			Promise.reject(formatMessage({ id: "risk.equipment_no_rule" }))
		} else {
			Promise.resolve()
		}
	}
	return Promise.resolve()
}

export const onlyLatinCharacter = (e: React.ChangeEvent<HTMLInputElement>) => {
	const { value } = e.target
	const latinOnly = /^[a-zA-Z0-9]*$/
	if (latinOnly.test(value) || value === "") {
		e.target.value = value
	}
}

export const onlyPasteLatinCharacter = (e: React.ClipboardEvent<HTMLInputElement>) => {
	const pastedData = e.clipboardData.getData("text")
	const latinOnly = /^[a-zA-Z0-9]*$/
	if (!latinOnly.test(pastedData)) {
		e.preventDefault()
	}
}

export const notAllowSpecialCharacters = (e: React.ChangeEvent<HTMLInputElement>, onNotAllow: Function) => {
	const newValue = e.target.value
	const regex = /[^a-zA-Z0-9.\u4e00-\u9fa5\s]/gu
	if (regex.test(newValue)) {
		onNotAllow(newValue.replace(regex, ""))
	}
}

export const onlyPositiveNumber = (e: React.ChangeEvent<HTMLInputElement>, onNotAllow: Function) => {
	const newValue = e.target.value
	const regex = /[^0-9]/g
	if (regex.test(newValue)) {
		onNotAllow(newValue.replace(regex, ""))
	}
}

export const onlyNumberAndHyphen = (e: React.ChangeEvent<HTMLInputElement>, onNotAllow: Function) => {
	const newValue = e.target.value
	const regex = /^-?\d*$/

	if (!regex.test(newValue)) {
		const sanitizedValue = newValue
			.replace(/[^0-9-]/g, "") // Remove non-numeric and non-hyphen characters
			.replace(/(?!^)-/g, "") // Remove hyphens that are not at the start

		onNotAllow(sanitizedValue)
	}
}

export const sanitizeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
	const { value } = e.target
	const nonLatinCharacters = /(\d+|\s)/
	if (nonLatinCharacters.test(value)) {
		e.target.value = value.replace(nonLatinCharacters, "")
	}
}

export const onlyPasteSanitizeCharacter = (e: React.ClipboardEvent<HTMLInputElement>) => {
	const pastedData = e.clipboardData.getData("text")
	const latinOnly = /^(\d+|\s)$/
	if (!latinOnly.test(pastedData)) {
		e.preventDefault()
	}
}
const notSpecial2 = (str: string) => {
	const specialKey = "#$&@/&*!~~!%^()_\\-+=<>?:\"{}|,./;'\\\\[\\]·~！@#￥%……&*（）——\\-+={}|《》？：“"
	for (let i = 0; i < str.length; i++) {
		if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
			return false
		}
	}
	return true
}

const isHaveEmoji = (str: string) => {
	const regex = emojiRegex()
	return !!regex.exec(str)
}

export const validateUser = (formatMessage: Function, value: string) => {
	const reg1 = /^[A-Za-z0-9]{4,11}$/
	const isSpecial = !notSpecial2(String(value))
	const isRmoji = isHaveEmoji(String(value))
	if (isSpecial) {
		return Promise.reject(formatMessage({ id: "risk.validate.no_space" }))
	} else if (isRmoji) {
		return Promise.reject(formatMessage({ id: "risk.validate.expression_is_not_supported" }))
	} else if (!value || !reg1.test(value)) {
		return Promise.reject(formatMessage({ id: "risk.validate.user_name_rules" }))
	}
	return Promise.resolve()
}

export const testUserName = (newFormat: Function, value: string) => {
	const reg1 = /^[A-Za-z0-9]{4,11}$/
	const isSpecial = !notSpecial2(value)
	const isEmoji = isHaveEmoji(value)

	if (isSpecial) {
		return Promise.reject(newFormat("agent.rule_other_tip2"))
	} else if (isEmoji) {
		return Promise.reject(newFormat("agent.rule_other_tip1"))
	} else if (!reg1.test(value)) {
		return Promise.reject(newFormat("agent.rule_input_tip4-11"))
	} else {
		return Promise.resolve()
	}
}

export const testApplyInfo = (newFormat: Function, value: string) => {
	const isSpecial = !notSpecial2(value)
	const isEmoji = isHaveEmoji(value)

	if (isSpecial) {
		return Promise.reject(newFormat("agent.rule_other_tip2"))
	} else if (isEmoji) {
		return Promise.reject(newFormat("agent.rule_other_tip1"))
	} else if (!value) {
		return Promise.reject(newFormat("agent.rule_input_tip_audit"))
	} else {
		return Promise.resolve()
	}
}

export const validateUserNames = (value: string): { result: any; err?: { type: TOAST_METHOD; msg: string | undefined } } => {
	let result = value.replace("，", ",").replace(/[^A-Za-z0-9\\,\\-]/g, "")
	let err: string | undefined = undefined

	if (!result) return { result: result }

	const userNamesList = result.split(",")
	const len = userNamesList.length

	if (len > 2 && userNamesList[len - 2] === "") {
		result = userNamesList.slice(0, len - 1).join(",")
	}

	if (len > 9) {
		err = "dxn.game_list.member_account_more_tips"
		result = userNamesList.slice(0, 9).join(",")
	}

	return {
		result,
		err: {
			type: "warning",
			msg: err
		}
	}
}

export const getInputValue = (str: string) => {
	const fractionReg = /\b\d+\/\d+\b/
	if (fractionReg.test(str) && Number(str.split("/")[1]) !== 0) return Number(str.split("/")[0]) / Number(str.split("/")[1])
	else if (!Number(str) && Number(str) !== 0) return "notValid"
	else if (Number(str) < 0) return "notValid"
	else return Number(str)
}
